package com.example.hanfu.firstpage;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class FirstTask implements Runnable{
    private static final String TAG = "FirstTask";
    Handler handler;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        Log.i(TAG, "run: ......");
        Document doc = null;

        try {
            doc = Jsoup.connect("https://hanfusong.com/").get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "doc:" + doc);
        Log.i(TAG, "title:" + doc.title());
         Element section = doc.getElementById("ajax_content");
        Log.i(TAG, "section=:" + section);
        Elements lis = section.getElementsByTag("li");
        Log.i(TAG, "lis=" + lis);
        //List<String> list1=new ArrayList<String>();
        List<HanFu> ret = new ArrayList<>();

        for (Element li : lis) {
            Elements as = li.getElementsByClass("imgeffect");
            Elements cont=li.getElementsByClass("excerpt");
            Log.i(TAG, "run:as=" + as);
            for(Element a:as){
                    Element imgs=a.getElementsByTag("img").get(0);
                    Log.i(TAG, "run:imgs=" + imgs);
                    String title = a.attr("title");
                    String href = a.attr("href");
                    String img=imgs.attr("data-original");
                    String content=cont.text();

                    Log.i(TAG, "run:href=" + href);
                    Log.i(TAG, "run:title=" + title);
                    Log.i(TAG, "run:img=" + img);
                    Log.i(TAG, "run:content=" + content);
              /*  try {
                    url = new URL(img);
                    InputStream is=url.openStream();
                    bitmap= BitmapFactory.decodeStream(is);
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

               */

                //Log.i(TAG, "run:img=" + img);
                    ret.add(new HanFu(title,href,img,content));
            }
        }
        Message msg = handler.obtainMessage(11, ret);
        handler.sendMessage(msg);
    }}